'use client';

import { useEffect, useState } from 'react';
import Image from 'next/image';
import { Button, Modal, Table, message } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import styles from './page.module.css';

interface Dish {
    id: string;
    name: string;
    image: string;
    price: number;
    description: string;
    tags: string[];
}

function TodayDishs() {
    const [dishes, setDishes] = useState<Dish[]>([]);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState<string | null>(null);
    const [isModalOpen, setIsModalOpen] = useState(false);
    const [allDishes, setAllDishes] = useState<Dish[]>([]);
    const [selectedDishIds, setSelectedDishIds] = useState<string[]>([]);
    const [modalLoading, setModalLoading] = useState(false);

    useEffect(() => {
        fetchTodayDishes();
    }, []);

    const fetchTodayDishes = async () => {
        try {
            const response = await fetch('/api/today-dishes');
            if (!response.ok) throw new Error('获取今日菜品失败');
            const data = await response.json();
            setDishes(data);
        } catch (err) {
            setError(err instanceof Error ? err.message : '获取今日菜品失败');
        } finally {
            setLoading(false);
        }
    };

    const fetchAllDishes = async () => {
        try {
            setModalLoading(true);
            const response = await fetch('/api/dishes');
            if (!response.ok) throw new Error('获取菜品列表失败');
            const data = await response.json();
            setAllDishes(data);
            // 预选当前的今日菜品
            setSelectedDishIds(dishes.map(dish => dish.id));
        } catch (err) {
            message.error('获取菜品列表失败');
        } finally {
            setModalLoading(false);
        }
    };

    const handleAddDishes = () => {
        setIsModalOpen(true);
        fetchAllDishes();
    };

    const handleModalOk = async () => {
        try {
            setModalLoading(true);
            const response = await fetch('/api/today-dishes', {
                method: 'PUT',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({ dishIds: selectedDishIds }),
            });

            if (!response.ok) throw new Error('更新今日菜品失败');
            
            message.success('更新今日菜品成功');
            setIsModalOpen(false);
            fetchTodayDishes(); // 刷新今日菜品列表
        } catch (err) {
            message.error('更新今日菜品失败');
        } finally {
            setModalLoading(false);
        }
    };

    const columns: ColumnsType<Dish> = [
        {
            title: '图片',
            dataIndex: 'image',
            key: 'image',
            width: 100,
            render: (image: string) => (
                <div className={styles.tableImage}>
                    <Image src={image} alt="菜品图片" width={60} height={60} />
                </div>
            ),
        },
        {
            title: '名称',
            dataIndex: 'name',
            key: 'name',
        },
        {
            title: '价格',
            dataIndex: 'price',
            key: 'price',
            render: (price: number) => `¥${price}`,
        },
        {
            title: '标签',
            dataIndex: 'tags',
            key: 'tags',
            render: (tags: string[]) => (
                <div className={styles.tableTags}>
                    {tags.map((tag, index) => (
                        <span key={index} className={styles.tableTag}>{tag}</span>
                    ))}
                </div>
            ),
        },
    ];

    if (loading) return <div className={styles.loading}>加载中...</div>;
    if (error) return <div className={styles.error}>{error}</div>;

    return (
        <div className={styles.container}>
            <div className={styles.header}>
                <h1 className={styles.title}>今日菜品</h1>
                <Button type="primary" onClick={handleAddDishes}>
                    添加今日菜品
                </Button>
            </div>

            {dishes.length === 0 ? (
                <div className={styles.emptyContainer}>
                    <div className={styles.emptyIcon}>🍽️</div>
                    <p className={styles.emptyText}>暂无今日菜品</p>
                </div>
            ) : (
                <div className={styles.dishGrid}>
                    {dishes.map((dish) => (
                        <div key={dish.id} className={styles.dishCard}>
                            <div className={styles.imageContainer}>
                                <Image
                                    src={dish.image}
                                    alt={dish.name}
                                    fill
                                    className={styles.image}
                                    sizes="(max-width: 768px) 100vw, (max-width: 1200px) 50vw, 33vw"
                                />
                            </div>
                            <div className={styles.dishInfo}>
                                <h3 className={styles.dishName}>{dish.name}</h3>
                                <p className={styles.dishPrice}>¥{dish.price}</p>
                                <div className={styles.dishTags}>
                                    {dish.tags.map((tag, index) => (
                                        <span key={index} className={styles.tag}>
                                            {tag}
                                        </span>
                                    ))}
                                </div>
                            </div>
                        </div>
                    ))}
                </div>
            )}

            <Modal
                title="选择今日菜品"
                open={isModalOpen}
                onOk={handleModalOk}
                onCancel={() => setIsModalOpen(false)}
                width={800}
                confirmLoading={modalLoading}
            >
                <Table
                    rowSelection={{
                        type: 'checkbox',
                        selectedRowKeys: selectedDishIds,
                        onChange: (selectedRowKeys) => {
                            setSelectedDishIds(selectedRowKeys as string[]);
                        },
                    }}
                    columns={columns}
                    dataSource={allDishes}
                    rowKey="id"
                    loading={modalLoading}
                />
            </Modal>
        </div>
    );
}

export default TodayDishs;